﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using SharpSvn;
using SharpSvn.UI;
using System.IO;

namespace LiveProjectManager.SRD.Services
{

    public class RepositoryService
    {
        public string getRepo()
        {
            string path = "https://live-project-manager.googlecode.com/svn/trunk";
            string dir = @"C:\Users\Rachid\Desktop";
            string projetctName = "Live Project Manager for tree";

            dir = Path.Combine(dir, projetctName);
            checkRepo(path, dir);

            return createJson(dir);
        }


        private void checkRepo(string path, string dir)
        {
            SvnClient svnClient = new SvnClient();
            SvnUriTarget target = new SvnUriTarget(path);

            if (!Directory.Exists(dir))
                svnClient.CheckOut(target, dir);
            else
                svnClient.Update(dir);
        }


        private string createJson(string dir)
        {
            return "[" + populateJson(dir) + "]";
        }


        private string populateJson(string dir)
        {
            DirectoryInfo directory = new DirectoryInfo(dir);
            string Json = "";


            DirectoryInfo[] directories = directory.GetDirectories();
            foreach (DirectoryInfo d in directories)
            {
                if (!d.Name.StartsWith("."))
                {
                    Json += "[{ \"data\" : \"";
                    Json += d.Name;
                    Json += "\", \"children\" : [";
                    Json += populateJson(d.FullName);
                    Json += "]}]";
                    if (!directories.Last().Equals(d))
                        Json += ",";
                }
            }

            FileInfo[] files = directory.GetFiles();

            if (directories.Length != 0 && files.Length != 0)
                Json += " , ";

            foreach (FileInfo f in files)
            {
                Json += " \"" + f.Name + "\" ";
                if (!files.Last().Equals(f))
                    Json += ",";
            }

            return Json;
        }
    }
}